var request = require('request');
var md5 = require('md5');
var db = require('../config/mongo_database');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');
var logger = require('../config/log4js').logger('access');

exports.signin = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';

	if(username == 'jinghaoran'){
		return res.sendStatus(401); 
	}

	db.userModel.findOne({username: username}, function (err, user) {
		console.log(user)
		if (err || null==user) {
			return res.sendStatus(401);
		}
		user.comparePassword(password, function(isMatch) {
			if (!isMatch) {
				return res.sendStatus(401);
            }
            var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
            redisClient.set(token, '{is_expired:false}');
            redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
			return res.json({token:token});
		});

	});
};

exports.register = async function(req, res) {
	var username = req.body.username || null;
	var password = req.body.password || null;
	var inviteid = req.body.inviteid || null;
	if(username == inviteid){
		return res.json({status:204, msg:'error'})
	}
	db.userModel.findOne({username: username}, function (err, user) {
		if (!user)
		{
			var user = new db.userModel();
			user.username = username;
			user.header   = 'https://www.bgncode.com/images/bgn/header/cat-0'+Math.round(Math.random()*9+1)+'.png';
			user.password = md5(password)
			user.save(function(err) {console.log(err)});
			if(inviteid!='' && inviteid!=username)
			invited(username, inviteid); // 邀请系统
		}
		var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
        redisClient.set(token, '{is_expired:false}');
        redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
		return res.json({status:200, token:token});
	});
	
}

// 修改密码
exports.me = function(req, res, next){
	var userid = tokenManager.getUserId(req);
	db.userModel.findOne({_id:userid}, 
		{username:1,email:1,header:1,score:1,grade:1,address:1}, 
		function (err, user) {
			res.json(user); 
	})
}

// 修改地址
exports.setAddr = function(req, res){
	var addr   = req.body.addr  || null;
	var index  = req.body.index || 0;
	var userid = tokenManager.getUserId(req);
	if(addr==null || index==null)
		return res.sendStatus(403);
	console.log(addr, index, userid)
	db.userModel.findOne({_id:userid}, function (err, user) {
		if(null!=user){
			user.address[index] = addr;
			db.userModel.update({_id:userid}, {$set:{address: user.address}}, function(err, pwduser){ // 执行变更
				return res.sendStatus(200); 
			})
		}else{
			return res.sendStatus(403);
		}
	})
}

// 修改密码
exports.setting = function(req, res, next){
	console.log(req.body)
	var password = req.body.password || '';
	var email    = req.body.email || '';
	var address  = req.body.address || '';
	var type  =  req.body.type || '';
	var update = {};
	if(type == 1)
		update = {password: md5(password)};
	else if(type == 2)
		update = {email: email};
	else if(type == 3)
		update = {address: address};
	console.log(update)
	var userid = tokenManager.getUserId(req);
	db.userModel.findOne({_id:userid}, function (err, user) {
		if(err) res.sendStatus(500); 
		if(null!=user){
			db.userModel.update({_id:userid}, {$set:update}, function(err, pwduser){ // 执行变更
				res.sendStatus(200); 
			})
		}
	})
}

exports.logout = function(req, res) {
	if (req.user) {
		tokenManager.expireToken(req.headers);

		delete req.user;	
		return res.sendStatus(200);
	}
	else {
		return res.sendStatus(401);
	}
}

// 好友邀请系统
function invited(username, inviteid){
	var log = new db.logModel();
	log.name="好友注册";
	log.content = username;
	log.msg = username + ';' + inviteid;
	log.save(function(err){});
	db.userModel.findOne({username: inviteid}, function (err, user) {
		if (user != null) {
			var invite = new db.inviteModel();
			invite.userid = username;
			invite.inviteid = inviteid;
			invite.score = 10;
			invite.save(function(err){});

			//更新积分
			user.score = user.score + 10;
			db.userModel.update({username: inviteid}, {$set:{score:user.score}}, function(err){
				logger.error("支付成功更新用户积分：",inviteid, err)
			})
		}
	});
}
